#!/usr/bin/env python

# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Utils for Street Identity Console application."""
import hashlib
from string import join

import urllib2
import uuid

__author__ = 'Maciej Machulak'
__maintainer__ = 'Maciej Machulak'
__email__ = 'mmachulak@google.com'

__copyright__ = 'Copyright 2012, Google Inc.'
__license__ = 'Apache License 2.0'
__version__ = '0.2'
__status__ = 'Prototype'


def random():
  """Generate a random string."""

  # TODO(mmachulak) change to something more secure
  return str(uuid.uuid4())


def get_bearer_token(header):
  """Extract Bearer token from the header."""

  return get_token(header)


def get_token(header, type='Bearer'):
  """Extract a token from the header."""

  header_prefix = join(['Authorization:', type, ''])
  field, sep, value = header.partition(header_prefix)
  if value:
    items = urllib2.parse_http_list(value)
    return items[0]
  return None

def get_token_hash(token):
  """Returns the token hash that can be stored in DB and used as an index."""

  return hashlib.sha256(token).hexdigest()